/*
 去掉空格
 */
String.prototype.trim = function() {
    return   this.replace(/(^\s*)|(\s*$)/g, "");
}
/*
 去掉左空格
 */
String.prototype.LTrim = function() {
    return   this.replace(/(^\s*)/, "");
}
/*
 去掉右空格
 */
String.prototype.RTrim = function() {
    return   this.replace(/(\s*$)/, "");
}

/*
 是否为空
 */
String.prototype.isEmpty = function() {
    return this.trim() == "";
}

/*
 endWith
 */
String.prototype.endWith = function(str) {
    if (!str || this == "" || str == "") return false;
    return   this.substring(this.length - str.length) == str;
}

/*
 字符替换
 */
String.prototype.replaceAll = function(AFindText, ARepText) {
    return this.replace(new RegExp(AFindText, "gm"), ARepText);
}

/**
 * format the string
 * for Example:
 * <pre>
 *     String.format("%1 love %2", "i", "you") -> i love you
 * <pre>
 * @param str string like "%1 love %2"
 */
String.format = function(str) {
    var args = arguments, re = new RegExp("%([1-" + args.length + "])", "g");
    return String(str).replace(
            re,
            function($1, $2) {
                return args[$2];
            }
            );
};

/**
 * format the string
 * for Example:
 * <pre>
 *     String.formatmodel("{i} love {you}", { i : "i", you : "you"}); -> i love you
 * </pre>
 * @param str
 * @param model
 */
String.formatModel = function(str, model) {
    for (var k in model) {
        var re = new RegExp("{" + k + "}", "g");
        str = str.replace(re, model[k]);
    }
    return str;
}
/*
 整数验证
 */
function validateInteger(value) {
    //var key = window.event ? e.keyCode:e.which;
    //var keychar = String.fromCharCode(key);
    reg = /\d/;
    return reg.test(value);
}
/*
 整数或小数验证
 */
function validateNum(value) {
    //var obj = window.event?e.srcElement:e.target;
    reg = /^[0-9]+\.?[0-9]+$/;
    return reg.test(value);
}

var waiting = false;
var isProcessing = false;
/*
 大遮罩
 */
function overLay(title, callback) {
    var win = $.ui.dialog.newDialog({"title":title,"modal":true,width:900,height:500});
    win.show();
    win.append(l("global_operation_executing"));
    if (callback)win.show(callback);
    isProcessing = true;
    waiting = true;
    return win;
}
/*
  小遮罩
 */
function miniOverLay(title, callback) {
    var win = $.ui.dialog.newDialog({"title":title,"modal":true,width:500,height:300});
    win.show();
    win.append(l("global_operation_executing"));
    if (callback)win.show(callback);
    isProcessing = true;
    waiting = true;
    return win;
}
/*
提示框
 */
function messageBox(message) {
    var win = $.ui.dialog.newDialog({"title":message,"modal":true,width:300,height:200});
    $("body").data("dialog").addButton({text:l("global_text_confirm")});
    win.show();
}

var success_counts = 0;
function ajaxOverLay(ajaxUrl, method, data, counts, completeHtml, operations, func) {
    $.ajax({
               type: method,
               timeout: 600000,
               url: ajaxUrl,
               cache: false,
               data: data,
               complete: function(response) {
                    if(response.status == 500 ||response.status == 400 ) {
                            var msg = "<br/>" + response.responseText.toString();
                            $("body").data("dialog").append(msg);
                            $("body").data("dialog").addButton({text:l("mo_text_back"),handler:'location.href = \"/mos\"'});
                            $("body").data("dialog").addButton({text:l("mo_text_close"),handler:'return true;'});
                           if (waiting) {
                               $("#task-startTip").remove();
                           }
                       }
                   else{
                   var msg = "<br/>" + response.responseText.toString();
                   $("body").data("dialog").append(msg);
                   success_counts++;
                   if (success_counts == counts) {
                       isProcessing = false;
                       success_counts = 0;
                       if (waiting) {
                           $("#task-startTip").remove();
                       }
                       $("body").data("dialog").append(completeHtml);
                       var btnHtmlArray = [];
                       $.each(operations, function(index, btn) {
                           $("body").data("dialog").addButton(btn);
                       });
                       if (func) {
                           func(response);
                       }
                   }}
               }
           });
}

function ajaxOverLayForProbe(ajaxUrl, method, data, counts, completeHtml, operations, func) {
    $.ajax({
               type: method,
               timeout: 600000,
               url: ajaxUrl,
               cache: false,
               data: data,
               complete: function(response) {
                   var msg = "<br/>" + response.responseText.toString();
                   $("body").data("dialog").append(msg);
                   success_counts++;
                   if (success_counts == counts) {
                       isProcessing = false;
                       success_counts = 0;
                       if (waiting) {
                           $("#task-startTip").remove();
                       }
                       $("body").data("dialog").append(completeHtml);
                       var btnHtmlArray = [];
                       $.each(operations, function(index, btn) {
                           $("body").data("dialog").addButton(btn);
                       });
                       if (func) {
                           func(response);
                       }
                   }}
           });
}

$(function() {
    $("body").quickTip();

    $(window).bind('beforeunload', function(event) {
        if (isProcessing) {
//            event.returnValue = "当前操作未完成，确定要离开？";
//            return "当前操作未完成，确定要离开？";
        }
    });
});


/**
 * created by zhj 2011-11-21
 *
 * encapsulate details of task
 *
 * */

$.ajaxTask = function(options) {
    $.extend(this, options);
};

$.ajaxTask.prototype = {
    url:"",
    method:"",
    params:{},
    paramsStr:"",
    tip:"",
    callback:$.noop(),
    run : function() {
        var self = this;
        var pArray = [];
        pArray[pArray.length] = "_method=" + (this.method ? this.method : "POST");
        for (var k in this.params)
            pArray[pArray.length] = k + "=" + this.params[k];
        var paramString = pArray.join("&");
        if (pArray.length == 1 && this.paramsStr)
            paramString = paramString + "&" + this.paramsStr;

        $.ajax({
                   type:"post",
                   timeout:300000,
                   url:this.url,
                   data:paramString,
                   contentType:'application/x-www-form-urlencoded;charset=UTF-8',
                   complete:function(response) {
                       //if(response.status != 200);
                       self.tip = response.responseText.toString();
                       self.callback.apply(self);
                   }
               });
    },
    getTip : function() {
        return this.tip;
    }
};

$.orderlyTaskExecutor = function(options) {
    $.extend(this, options);
    this._initWidget();
};

$.orderlyTaskExecutor.prototype = {
    actions:[],
    cancelable:true,
    endTip:l("global_operation_finished"),
    processDialog:null,
    startTip:l("global_operation_executing"),
    suspended:false,
    finished:false,
    suspendTip:l("global_operation_suspend"),
    suspendConfirm:l("global_operation_confirm"),
    tasks:[],
    title:"",
    start : function() {
        this.finished = false;
        this.processDialog.show();
        this.processDialog.append(this.startTip);
        this._checkTask();
    },
    stop : function() {
        this.suspended = true;
    },
    _end : function(ended) {
        if(!this.finished){
            this.finished = true;

            var self = this;
            $("#task-startTip").remove();

            $(this.actions).each(function(index, action) {
                self.processDialog.addButton(action);
            });

            if(ended)
                this.processDialog.append(this.endTip);
            else
                this.processDialog.append(this.suspendTip);
        }
    },
    _initWidget:function() {
        var self = this;
        this.processDialog = $.ui.dialog.newDialog({
                                                       "title":this.title,"modal":true,width:900,height:500,closable:this.cancelable,
                                                       closeConfirmCb : function(resultCb) {
                                                           if(self.isConfirming)
                                                                return;

                                                           if(!self.finished) {
                                                               self.isConfirming = true;
                                                               $.ui.messageBox.show({title:l("global_text_confirm"),msg:self.suspendConfirm,
                                                                                        buttons:$.ui.messageBox.OKCANCEL,
                                                                                        el:this.bodyElement,
                                                                                        callback: function(result) {
                                                                                           self.isConfirming = false;
                                                                                           if ($.ui.messageBox.OK[result]) {
                                                                                               self.suspended = true;
                                                                                           }

                                                                                           self._checkTask();
                                                                                        }
                                                               });
                                                           }
                                                           else
                                                               resultCb(true);
                                                       }
                                                   });
    },
    _checkTask : function() {
        if(this.isConfirming)
           return;

        var task = this.tasks.pop();
        if (!this.suspended) {
            if (task) {
                task.run();
            }
            else {
                this._end(true);
            }
        }
        else {
            this._end(false);
        }
    },
    _taskCallback : function(task) {
        this.processDialog.append(task.getTip()+"<br>");
        this._checkTask();
    },
    addTask: function(taskCfg) {
        var task = new $.ajaxTask(taskCfg);
        task.callback = $.createDelegate(this._taskCallback, this, [task]);
        this.tasks.push(task);
    }
};

$.orderlyTaskExecutor.create = function(options) {
    return new $.orderlyTaskExecutor(options);
};

var goBack = function() {
        history.go(-1);
};
var  rollBack = function() {
        location.href = "/assign_rules";
};

var serializeForm =  function() {
        var mo_type = $("input[name='moType']").attr("value");
        var rule_name = $("#AssignRule_name").attr("value");
        var engine_key = $("select[name='AssignRule/engine/key']").val();
        var rule_desc = $("#AssignRule_description").attr("value");
        var a = {"vv":"cc"} + {"bb":"xxx"};
        var checkArray = [];
        var checkData = "";
        var acount=0;
        $("form[name='AssignRule']").find("input[type='checkbox']").each(function() {
            if($(this).is(":checked")){
            var id = $(this).attr("id");
                var data;
                var expression= 'expression/'+id;
                var endPoint = 'endPoint/'+id;
                var and = 'and/'+id;
                var max =  'max/'+id;
                data = "'"+expression +"':'"+$("select[name='expression/"+id+"']").val()+"','"+endPoint +"':'"+ $("input[name='endPoint/"+id+"']").attr("value")+ "','" +and+"':'"+$("label[name='and/"+id+"']").text()+"','"+ max +"':'" + $("input[name='max/"+id+"']").attr("value")+"'";
                checkArray[acount] = data;
                acount++;
            }
        });
        for(var i =0;i<checkArray.length;i++){
            checkData += checkArray[i];
            if(i != checkArray.length){
                checkData += ',';
            }
        }
        checkData = '{' + checkData + '}';
        return  {"moType":mo_type,"AssignRule/name":rule_name,"AssignRule/engine/key":engine_key,"AssignRule/description":rule_desc,"checkData":eval('('+checkData+')')}
};

function edit(id) {
    $.ajax({
       method:'GET',
        url:'/mos/edit/'+id,
        complete: function(response) {
                if(response.status == 500) {
                    overLay(l("global_text_tips"));
                    var msg = "<br/>" + response.responseText.toString();
                    $("body").data("dialog").append(msg);
                    $("body").data("dialog").remove(l("global_operation_executing"));
                    $("body").data("dialog").addButton({text:l("global_text_confirm")});
                    $("body").data("dialog").addButton({text:l("global_text_cancel")});
                }else if(response.status == 200) {
                    location.href = '/mos/edit/'+id;
                }
           }
       });
}

function openSelfmanaging() {
    var baseUrl = window.location.href;
    var url = baseUrl.substring(0,baseUrl.lastIndexOf(":"));
    window.open(url+":8030",l("selfmanaging_window_name"));
}